package com.nicefact.mailmonitor.dao;

import java.util.ArrayList;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import org.springframework.stereotype.Component;

import com.google.appengine.api.datastore.Key;
import com.nicefact.mailmonitor.entity.AppAdmin;

@Component
public class AppAdminDao  extends AbstractDao<AppAdmin>{

	public AppAdmin get(String email) {
		PersistenceManager pm = super.getPersistenceManager();		
		Query query = pm.newQuery(AppAdmin.class);
		query.declareParameters("String userMail");
		query.setFilter("email==userMail");
		AppAdmin obj = null;
		try {
			List<AppAdmin> results = (List<AppAdmin>) query.execute(email);
			if (!results.isEmpty()) {
				obj = pm.detachCopy(results.get(0));
			}
		} finally {
			query.closeAll();
			pm.close();
		}
		
		
		return obj;
	}
	
	public AppAdmin getByKey(Key key) {
		return super.get(AppAdmin.class, key);
	}
	
	public AppAdmin save(AppAdmin appAdmin) {
		AppAdmin	obj = super.create(appAdmin);
		return obj;
	}
	
	public List<AppAdmin> getAll(){
		PersistenceManager pm = getPersistenceManager();
		Query query =  pm.newQuery(AppAdmin.class);
		List<AppAdmin> objectList = new ArrayList<AppAdmin>();
		int start = 0;
		int max = 800;
		try{
			while (true) {
				query.setRange(start, start + max);
				List<AppAdmin> results = (List<AppAdmin>) query.execute();
				if (results.isEmpty()) {
					break;
				} else {
					objectList.addAll(pm.detachCopyAll(results));
					start += max;
				}
			}
		}finally{
			query.closeAll();
			pm.close();
		}
		return objectList;
	}
}
